﻿using System;
using System.Collections.Generic;

using FireBus.Contracts;


namespace FireBus.Extensions.ExtensionStorage
{
	public class Extension :
		IEventListener<ExtensionStorageInitialize>,
		IRequestListener<ExtensionListRequest, ExtensionListResponse>,
		IRequestListener<ExtensionStateRequest, ExtensionStateResponse>,
		IEventListener<ExtensionLoadEvent>,
		IEventListener<ExtensionUnloadEvent>
	{
		private IStorage _Storage;


		public void OnEvent(ExtensionStorageInitialize args)
		{
			if (args == null)
			{
				throw new ArgumentNullException("args");
			}
			_Storage = args.Storage;
		}

		public ExtensionListResponse OnRequest(ExtensionListRequest request)
		{
			if (request == null)
			{
				throw new ArgumentNullException("request");
			}
			IEnumerable<ExtensionToken> extesions =
				_Storage == null ? null : _Storage.GetExtensions();
			return new ExtensionListResponse(extesions);
		}

		public ExtensionStateResponse OnRequest(ExtensionStateRequest request)
		{
			if (request == null)
			{
				throw new ArgumentNullException("request");
			}
			var state = _Storage == null ? ExtensionState.NotAvailable : _Storage.GetExtensionState(request.Name);
			return new ExtensionStateResponse(state);
		}

		public void OnEvent(ExtensionLoadEvent args)
		{
			if (args == null)
			{
				throw new ArgumentNullException("args");
			}
			if (_Storage == null)
			{
				return;
			}
			_Storage.LoadExtension(args.Name);
		}

		public void OnEvent(ExtensionUnloadEvent args)
		{
			if (args == null)
			{
				throw new ArgumentNullException("args");
			}
			if (_Storage == null)
			{
				return;
			}
			_Storage.UnloadExtension(args.Name);
		}
	}
}
